package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.UserContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zzw
 * @date 2025/5/16
 * @description 订单服务实现
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    //    @Autowired
    //    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    public static Long staticOrderId;

    /**
     * 分页查询订单
     *
     * @param ordersPageQueryDTO 查询条件
     * @return PageResult<Orders>
     */
    @Override
    public PageResult<OrderVO> page(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 1.设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 2.执行分页查询
        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);

        List<OrderVO> orderVOList = null;
        // 3.将page中的orders列表封装成OrderVO列表
        if (page.getResult() != null && !page
                .getResult()
                .isEmpty()) {
            orderVOList = getOrderVOList(page);
        }

        // 4.返回封装后的结果
        return new PageResult<>(page.getTotal(), orderVOList);
    }

    /**
     * 获取订单列表
     *
     * @param page 页码
     * @return List<OrderVO>
     */
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        return page
                .getResult()
                .stream()
                .map(order -> {
                    OrderVO orderVO = new OrderVO();
                    BeanUtils.copyProperties(order, orderVO);
                    List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailByOrderId(order.getId());
                    orderVO.setOrderDetailList(orderDetailList);
                    orderVO.setOrderDishes(getOrderDishesStr(order));
                    return orderVO;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取订单菜品信息字符串
     *
     * @param orders 订单信息
     * @return 菜品信息
     */
    public String getOrderDishesStr(Orders orders) {
        // 1.根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailByOrderId(orders.getId());

        // 2.将订单菜品信息拼接成字符串
        List<String> dishesStr = orderDetailList
                .stream()
                .map(orderDetail -> orderDetail.getName() + "*" + orderDetail.getNumber() + ";")
                .collect(Collectors.toList());
        return String.join("", dishesStr);

    }


    /**
     * 根据id查询订单
     *
     * @param id 订单id
     * @return Orders
     */
    @Override
    public OrderVO getById(Long id) {
        OrderVO orderVO = new OrderVO();

        // 1. 根据id查询订单和订单详情
        Orders orders = orderMapper.getOrderById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailByOrderId(id);

        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }


    /**
     * 取消订单
     *
     * @param ordersCancelDTO 取消订单的参数
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 1.根据id查询订单
        Orders orders = orderMapper.getOrderById(ordersCancelDTO.getId());

        if (orders == null) {
            // 订单不存在
            throw new RuntimeException("订单不存在");
        }

        // 2.检查订单状态，确保订单可以取消

        // 3.更新订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());

        // 4.保存更新后的订单
        orderMapper.update(orders);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return OrderStatisticsVO
     */
    @Override
    public OrderStatisticsVO getOrderStatistics() {
        return orderMapper.getOrderStatistics();
    }

    /**
     * 完成订单
     *
     * @param id 订单id
     */
    @Override
    public void complete(Long id) {
        // 1.根据id查询订单
        Orders orders = orderMapper.getOrderById(id);

        if (orders == null) {
            // 订单不存在
            throw new RuntimeException("订单不存在");
        }

        if (!orders
                .getStatus()
                .equals(Orders.DELIVERY_IN_PROGRESS)) {
            // 订单状态错误
            throw new RuntimeException("订单状态错误");
        }

        // 2.修改订单信息
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        // 3.更新订单信息
        orderMapper.update(orders);
    }

    /**
     * 订单拒绝
     *
     * @param rejectionDTO 拒绝订单的参数
     */
    @Override
    public void reject(OrdersRejectionDTO rejectionDTO) {

        // 1.根据id查询订单
        Orders orders = orderMapper.getOrderById(rejectionDTO.getId());

        if (orders == null) {
            // 订单不存在
            throw new RuntimeException("订单不存在");
        }
        if (!orders
                .getStatus()
                .equals(Orders.TO_BE_CONFIRMED)) {
            // 订单状态错误
            throw new RuntimeException("订单状态错误");
        }

        // 2.修改订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(rejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        // 3.更新订单信息
        orderMapper.update(orders);
    }

    /**
     * 订单确认
     *
     * @param confirmDTO 确认订单的参数
     */
    @Override
    public void confirm(OrdersConfirmDTO confirmDTO) {
        // 1.根据id查询订单
        Orders orders = orderMapper.getOrderById(confirmDTO.getId());

        if (orders == null) {
            // 订单不存在
            throw new RuntimeException("订单不存在");
        }
        if (!orders
                .getStatus()
                .equals(Orders.TO_BE_CONFIRMED)) {
            // 订单状态错误
            throw new RuntimeException("订单状态错误");
        }

        // 2.修改订单状态
        orders.setStatus(Orders.CONFIRMED);

        // 3.更新订单信息
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id 订单id
     */
    @Override
    public void delivery(Long id) {
        // 1.根据id查询订单
        Orders orders = orderMapper.getOrderById(id);

        if (orders == null) {
            // 订单不存在
            throw new RuntimeException("订单不存在");
        }
        if (!orders
                .getStatus()
                .equals(Orders.CONFIRMED)) {
            // 订单状态错误
            throw new RuntimeException("订单状态错误");
        }

        // 2.修改订单状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        // 3.更新订单信息
        orderMapper.update(orders);
    }


    // 提交订单
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 处理各种业务异常（地址簿为空，购物车数据为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            // 抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 查询当前用户的购物车数据
        Long userId = UserContext.getUserId();

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);

        if (shoppingCartList == null || shoppingCartList.isEmpty()) {

            // 抛出业务异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 向订单表插入1条数据

        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);

        orderMapper.insert(orders);

        // 获取订单id
        staticOrderId = orders.getId();


        // 向订单明细表插入n条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();

        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());

            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetailList);

        // 清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);

        // 封装一个OrderSubmitVO返回


        return OrderSubmitVO.builder()
                            .id(orders.getId())
                            .orderTime(orders.getOrderTime())
                            .orderNumber(orders.getNumber())
                            .orderAmount(orders.getAmount())
                            .build();
    }


    // 订单催单
    @Override
    public void reminder(Long id) {

        // 根据id查询订单
        Orders ordersDB = orderMapper.getOrderById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map<String, Object> map = new HashMap<>();
        // 1表示来电提醒，2表示客户催单
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + ordersDB.getNumber());

        // 通过websocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }


    // 再来一单
    @Override
    public void repetition(Long id) {

        // 查询当前用户id
        Long userId = UserContext.getUserId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    // 历史订单分页查询
    @Override
    public PageResult<OrderVO> pageQueryUser(int page, int pageSize, Integer status) {

        // 设置分页
        PageHelper.startPage(page, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(UserContext.getUserId());
        ordersPageQueryDTO.setStatus(status);

        // 分页查询
        Page<Orders> page1 = orderMapper.page(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page1 != null && page1.getTotal() > 0) {

            for (Orders orders : page1) {
                // 获取订单id
                Long orderId = orders.getId();

                // 查询订单明细
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);

                // 封装OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);

                list.add(orderVO);

            }

        }
        if (page1 != null) {
            return new PageResult(page1.getTotal(), list);
        }
        return null;
    }

    // 用户取消订单
    @Override
    public void userCancelById(Long id) {

        // 根据id查询订单
        Orders ordersDB = orderMapper.getOrderById(id);

        // 判断订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 订单状态判断
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }


        // 订单处于待接单状态下取消，需要退款
        Orders orders = new Orders();
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口

            //支付状态修改为退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);


    }

    // 查询订单详情
    @Override
    public OrderVO details(Long id) {

        // 根据id查询订单
        Orders orders = orderMapper.getOrderById(id);

        // 查询该订单对应的订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装成OrderVO进行返回
        OrderVO orderVO = new OrderVO();

        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO 订单支付参数
     * @return OrderPaymentVO
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        //        Long userId = UserContext.getUserId();
        //        User user = userMapper.getById(userId);

        // 跳过调用支付接口，模拟支付成功
        //        //调用微信支付接口，生成预支付交易单
        //        JSONObject jsonObject = weChatPayUtil.pay(
        //                //商户订单号
        //                ordersPaymentDTO.getOrderNumber(),
        //                //支付金额，单位 元
        //                new BigDecimal(0.01),
        //                //商品描述
        //                "苍穹外卖订单",
        //                //微信用户的openid
        //                user.getOpenid()
        //                                                 );
        //
        //        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //            throw new OrderBusinessException("该订单已支付");
        //        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        Orders order =
                Orders.builder().id(staticOrderId).payStatus(Orders.PAID).status(Orders.TO_BE_CONFIRMED)
                      .checkoutTime(LocalDateTime.now())
                      .build();

        // 修改订单状态
        orderMapper.update(order);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 订单号
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = UserContext.getUserId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                              .id(ordersDB.getId())
                              .status(Orders.TO_BE_CONFIRMED)
                              .payStatus(Orders.PAID)
                              .checkoutTime(LocalDateTime.now())
                              .build();

        orderMapper.update(orders);

        Map<String, Object> map = new HashMap<>();
        //消息类型，1表示来单提醒
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}















